<?php
namespace backend\service ;
use backend\models\AdminUser;
use backend\models\Column;
use common\service\ConstatService;
use yii\db\Query ;
use Yii ;
use yii\helpers\ArrayHelper;
use yii\web\Cookie;
use yii\web\ForbiddenHttpException;

//权限服务
class AuthService {

    public static function findItemChildByUserId($user_id){
        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_assignment}}")
            ->where(["user_id"=>$user_id]) ;

        $role_obj = $query->one() ;
        if(empty($role_obj['item_name'])){
            return [] ;
        }else{
            $role = $role_obj['item_name'] ;
        }

        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_item_child}}") ;

        if(!empty($role)){
            $query->andWhere(["parent"=>$role]) ;
        }
        $childs = $query->all() ;

        $control_arr = [] ;
        foreach($childs as $child){
            $item = $child['child'] ;
            $item_arr = explode("/",$item) ;
            if(!empty($item_arr[0])&& in_array($item_arr[0],$control_arr)==false){
                array_push($control_arr,$item_arr[0]) ;
            }
        }

        return $control_arr ;
    }

    /**
     * 获取用户权限
     * @param $user_id
     * @return array
     */
    public static function findUserAuths($user_id){
        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_assignment}}")
            ->where(["user_id"=>$user_id]) ;

        $role_obj = $query->one() ;
        if(empty($role_obj['item_name'])){
            return [] ;
        }else{
            $role = $role_obj['item_name'] ;
        }

        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_item_child}}") ;

        if(!empty($role)){
            $query->andWhere(["parent"=>$role]) ;
        }
        $childs = $query->all() ;
        $auths = ArrayHelper::getColumn($childs,"child") ;
        return $auths;
    }

    /**
     * 获取用户登陆后的地址
     */
    public static function getUserLoginUrl($username,$user_id){
        $top_column_arr = ColumnService::findColumnList(null,1,0) ;
        $url = null ;
        if($username!="admin"){
            $moduleNameArr = array_keys(Yii::$app->modules) ;
            $controller_arr = AuthService::findItemChildByUserId($user_id) ;
            if(!empty($controller_arr[0])){
                foreach($top_column_arr['list'] as $val){
                    if(in_array($val['tag'],$controller_arr)){
                        if(in_array($val['tag'],$moduleNameArr)){
                            //模块
                            $url = "/".$val['tag'] ;
                            self::addLoginUrlCookie($url) ;
                            return $url  ;
                        }else{
                            $controller = $val['tag'] ;
                            $action = self::getFirstActionByController($controller,$user_id) ;
                            $action = empty($action)?"":$action ;
                            $url = "/{$controller}/{$action}" ;
                            self::addLoginUrlCookie($url) ;
                            return $url  ;
                        }
                    }
                }
            }
        }else{
            //admin账号
            if(!empty($top_column_arr)){
                $controller = $top_column_arr['list'][0]['tag'];
                $action = self::getFirstActionByController($controller,$user_id,$username) ;
                $action = empty($action)?"":$action ;
                $url = "/{$controller}/{$action}" ;
                self::addLoginUrlCookie($url) ;
                return $url  ;
            }else{
                $url = "/site/index" ;
                self::addLoginUrlCookie($url) ;
                return $url;
            }
        }

        if(empty($url)){
            throw new ForbiddenHttpException("暂无权限") ;
        }
    }

    /**
     * 获取方法
     * @param $controller
     * @return mixed|null
     */
    public static function getFirstActionByController($controller,$user_id,$username=null){
        $column = Column::findOne(["tag"=>$controller,"pid"=>0]) ;
        if(empty($column)){
            return null ;
        }

        $subColumn = Column::find()->where(["pid"=>$column['id']])->orderBy("order asc,id asc")->asArray()->all() ;
        if(empty($subColumn)){
            return null ;
        }

        $action_arr = AuthService::findSubItemByUserIdController($user_id,$controller) ;
        foreach($subColumn as $val){
            if(in_array($val['tag'],$action_arr)){
                return $val['tag'] ;
            }
        }

        if(!empty($username) && $username=="admin"){
            return empty($subColumn[0]['tag'])?"index":$subColumn[0]['tag'];
        }else{
            return null ;
        }
    }

    /**
     * 记录登陆的路径
     * @param $url
     */
    public static function addLoginUrlCookie($url){
        $cookies = Yii::$app->response->cookies;
        $cookie = new Cookie();
        $cookie->name = 'defaultUrl';
        $cookie->value = $url ;
        $cookies->add($cookie);
    }

    /**
     * @param $user_id
     * @return array
     */
    public static function findSubItemByUserIdController($user_id,$controller){
        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_assignment}}")
            ->where(["user_id"=>$user_id]) ;

        $role_obj = $query->one() ;
        if(empty($role_obj['item_name'])){
            return [] ;
        }else{
            $role = $role_obj['item_name'] ;
        }

        $query = new Query() ;
        $pages = null ;
        $select = "*" ;
        $query->select($select)
            ->from("{{%auth_item_child}}") ;

        if(!empty($role)){
            $query->andWhere(["parent"=>$role]) ;
        }
        $childs = $query->all() ;

        $action_arr = [] ;
        foreach($childs as $child){
            $item = $child['child'] ;
            $item_arr = explode("/",$item) ;
            if(strpos($item,$controller)!==false){

            }
            if(!empty($item_arr[1])&& strpos($item,$controller)!==false){
                array_push($action_arr,$item_arr[1]) ;
            }
        }
        return $action_arr ;
    }

    /**
     * 检查连接是否有权限
     * @param $userId
     * @param $item
     * @return bool
     */
    public static function checkUserAuth($userId,$item){
        $user = AdminUser::findOne(["user_id"=>$userId]) ;
        if(empty($user)){
            return false ;
        }
        //超级管理员有权限
        if($user['type_id']==ConstatService::ADMIN_USER_TYPE_ID_SUPER_ADMIN || $user['username']=="admin" ){
            return true ;
        }

        $datas = Yii::$app->cache->get("auth_item_child_".$user['type_id']) ;
        if(empty($datas)){
            $role = $user['role'] ;

            $query = new Query() ;
            $pages = null ;
            $select = "*" ;

            $query->select($select)
                ->from("{{%auth_item_child}}")
                ->andWhere(["parent"=>$role]) ;

            $datas = $query->all() ;

            if(!empty($datas)){
                Yii::$app->cache->set("auth_item_child_".$user['type_id'],$datas,300) ;
            }
        }

        $arr = ArrayHelper::getColumn($datas,"child") ;

        if(in_array($item,$arr)){
            return true ;
        }else{
            return false ;
        }

    }

}
